/*
 * graph2D
 * Copyright (c) 2009 Shun Moriya <shun@mnu.sakura.ne.jp>
 *
 * The MIT License
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "common.h"
#include "abort.h"
#include <stdio.h>
#include <string.h>

#if defined(TARGET_WINDOWS)
 #if !defined(_DEBUG)
  #define _CRT_SECURE_NO_WARNINGS
 #endif
 #include <windows.h>
 #include "platform/windows/abort_impl.h"
 #define MESSAGE		const wchar_t*
#elif defined(TARGET_IPHONE)
 #include "platform/iOS/abort_impl.h"
 #define MESSAGE		const char*
#endif

namespace Graph2D
{
	static MESSAGE* errorMessageArray[ERROR_CODE_SIZE] = {
		&errorMessages[0],
		&errorMessages[1],
		&errorMessages[1],
		&errorMessages[1],
		&errorMessages[2],
		&errorMessages[3],
		&errorMessages[3],
		&errorMessages[3],
		&errorMessages[3],
	};

	void abort(const ERROR_CODE errorCode, const char* hint)
	{
#if defined(TARGET_WINDOWS)
		static MESSAGE errorTitle = L"ERROR";
		wchar_t message[512];
		::swprintf_s(message, sizeof(message), L"%s (%d)", errorMessageArray[errorCode], errorCode);
		if(hint)
		{
			size_t size = strlen(hint) + 1;
			size_t result = 0;
			wchar_t w_hint[512];
			mbstowcs_s(&result, w_hint, size, hint, _TRUNCATE);
			wcscat_s(message, sizeof(message), L" ... ");
			wcscat_s(message, sizeof(message), w_hint);
		}
		Windows::abort_impl(message);

#elif defined(TARGET_IPHONE)
		char message[512];
		::sprintf(message, "%s (%d)", *errorMessageArray[errorCode], errorCode);
		if(hint)
		{
			strcat(message, " ... ");
			strcat(message, hint);
		}
		Implementation::abort_impl(message);
#endif
	}
}
